from rest_framework import serializers
from apps.app01.models import Product


class AddToCartSerializer(serializers.Serializer):
    productId = serializers.IntegerField()
    count = serializers.IntegerField()
    # config 存的是一个列表，里面是若干{name, choice}的字典
    config = serializers.ListField(
        child=serializers.DictField(),
        required=False
    )

    def validate_count(self, value):
        if value <= 0:
            raise serializers.ValidationError("商品数量必须大于0")
        return value

    def validate(self, attrs):
        product_id = attrs.get('productId')
        # 验证商品是否存在
        if not Product.objects.filter(id=product_id).exists():
            raise serializers.ValidationError(f"ID为 {product_id} 的商品不存在！")
        return attrs
